<?php

namespace Boosen\Company\app\Console\Commands;

use Illuminate\Console\Command;

use App\Models\Region;
use Log;

use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;

class InfoSpider extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'company:info:spider ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $nextPage = 1;
        $canBreak = false;
        while (true) {
            $citys = Region::ofType(1)->simplePaginate(2, ['*'], 'page', $nextPage)->toArray();
            try {
                $nextPage++;
                Log::channel('company')->info("going to page " . $citys['current_page']);

                foreach ($citys['data'] as $city) {
                    $queryArr = array(
                        'keywords' => iconv('UTF-8', 'gb2312', '包装机械'),
                        'sortType' => 'manufacture',
                        'province' => iconv('UTF-8', 'gb2312', $city['name']),
                        // 'biztype' => 1,
                        'pageSize' => 30,
                        // 'offset' =>  3
                        'beginPage' => 1
                    );

                    $canBreak = $this->baseUrlFetch($queryArr);
                    echo 123;
                    exit;

                }

                if ($canBreak or count($citys['data']) == 0) break;

            } catch (\Exception $e) {
                echo $e->getMessage();
                break;
                Log::channel('company')->error("Failed going to page " . $citys['current_page']);
            }
        }
        
    }


    private function baseUrlFetch($queryArr)
    {
        $beginPage = 1;
        while (true) {
            $queryArr['beginPage'] = 1;

            $url = config('boosen.company.1688_main_url') . '?' . http_build_query($queryArr);
            try {
                $client = new Client();
                $guzzleClient = new GuzzleClient(array(
                    'timeout' => 30,
                ));
                $client->setClient($guzzleClient);
                $crawler = $client->request('GET', $url);
            } catch (\Exception $e) {
                echo $e->getMessage();
                break;
                exit;
            }
        }
    }
}
